<template>
  <div>
    <van-sticky>
      <van-nav-bar title="登录页面" left-arrow @click-left='backOff' />
    </van-sticky>
    <van-row style='margin-top: 24vh'>
      <van-col span='24'>
        <van-form @submit="onSubmit">
          <van-field
            input-align="right"
            v-model="username"
            name="username"
            :label="token ? '账号' : '学号'"
            :placeholder="token ? '账号' : '学号'"
            clearable
            :rules="[{ required: true, message: '请填写学号' }]"
          />
          <van-field
            input-align="right"
            v-model="password"
            type="password"
            name="password"
            :label="token ? '特殊密码' : '密码'"
            :placeholder="token ? '特殊密码' : '密码'"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <van-field name="switch" label="管理员模式" input-align="right">
            <template #input>
              <van-switch v-model="token" size="20" />
            </template>
          </van-field>
          <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit">提交</van-button>
          </div>
        </van-form>
      </van-col>
      <van-col span='12' offset='6'>
        <van-button block plain to='register' class="register-btn">学号无法登录? 前往注册</van-button>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import { request } from 'network/request'

export default {
  name: 'Login',
  data() {
    return {
      token: false,
      username: '',
      password: '',
    }
  },
  methods: {
    backOff() {
      this.$router.go(-1)
    },
    onSubmit() {
      // 通过 axios 携带登录数据发送请求
      // 缺少滑块填充拼图验证码
      request({
        url: 'user/success',
        method: 'post',
        params: {
          token: this.token ? 'admin' : 'user',
          username: this.username,
          password: this.password
        }
      }).then((res) => {
        // 将 res.data 保存到 vuex 中
        // 之后改进就是换成 vuex 的 actions 中的函数来操纵数据
        if(res.data.length == 1) {
          this.$store.dispatch('dataInput',res.data[0])
          this.$toast.success('登录成功')
          // 改进的时候出现一个遮罩层 + 跳转主页的提示
          setTimeout(() => {
            this.$router.push('home')
          }, 1000)
        } else {
          this.$toast.fail('请检查输入')
        }
      })
      .catch((err) => console.log(err))
    },
  }
}
</script>

<style scoped>
/* @import url(); 引入css类 */
.register-btn {
  background-color: #eee;
  color: #1989fa;
}
</style>
